package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    
    @Override
    public void add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressBookMapper.list(BaseContext.getCurrentId());
        if (list == null || list.size() == 0) {
            addressBook.setIsDefault(1);
            addressBookMapper.add(addressBook);
        }
        else{
            addressBook.setIsDefault(0);
            addressBookMapper.add(addressBook);
        }
    }

    @Override
    public List<AddressBook> list() {
        Long userId = BaseContext.getCurrentId();
        return addressBookMapper.list(userId);
    }

// ... existing code ...
    @Override
    @Transactional
    public void setDefault(int id) {
        Long userId = BaseContext.getCurrentId();
        //获得默认地址
        AddressBook addressBook = addressBookMapper.getDefault(userId);
        addressBook.setIsDefault(0);
        addressBookMapper.update(addressBook);
        //先设置指定地址为默认
        addressBookMapper.setDefault(userId, id);
    }

    @Override
    public AddressBook getDefault(Long currentId) {
        return addressBookMapper.getDefault(currentId);
    }

    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        AddressBook addressBook1 = addressBookMapper.getById(addressBook.getId());
        addressBook.setIsDefault(addressBook1.getIsDefault());
        addressBookMapper.update(addressBook);
    }

    @Override
    public void delete(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        if (addressBook.getIsDefault() == 1) {
            addressBookMapper.delete(id);
            List<AddressBook> list = addressBookMapper.list(BaseContext.getCurrentId());
            if (list != null && list.size() > 0) {
                //将第一个地址设置为默认
                AddressBook addressBook1 = list.get(0);
                addressBook1.setIsDefault(1);
                addressBookMapper.update(addressBook1);
            }
        }
    }

}
